package uestc.lj.gulishop.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import uestc.lj.common.constant.CartConstant;
import uestc.lj.common.utils.R;
import uestc.lj.gulishop.cart.feign.ProductFeignService;
import uestc.lj.gulishop.cart.interceptor.CartInterceptor;
import uestc.lj.gulishop.cart.service.CartService;
import uestc.lj.gulishop.cart.to.UserInfoTO;
import uestc.lj.gulishop.cart.vo.Cart;
import uestc.lj.gulishop.cart.vo.CartItem;
import uestc.lj.gulishop.cart.vo.SkuInfoVO;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author:Crazlee
 * @Date:2021/6/11
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        // 1.获取到要操作的购物车
        BoundHashOperations<String, Object, Object> operations = getCartOps();

        // 判断此商品是否在购物车中存在
        String result = (String) operations.get(skuId.toString());
        if (!StringUtils.isEmpty(result)) {
            // 购物车已有此商品，直接修改数量即可
            CartItem cartItem = JSON.parseObject(result, CartItem.class);
            Integer count = cartItem.getCount();
            cartItem.setCount(count + num);
            operations.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }
        // 添加购物车中没有的商品
        CartItem cartItem = new CartItem();
        CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
            // 2.远程查询当前要添加的商品的信息
            R r = productFeignService.info(skuId);
            if (r.getCode() == 0) {
                SkuInfoVO skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVO>() {
                });
                // 3.添加到购物车
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfo.getPrice());

            }
        }, threadPoolExecutor);

        CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
            // 4.远程查询sku的组合信息
            R r = productFeignService.getSkuSaleAttrValues(skuId);
            if (r.getCode() == 0) {
                List<String> skuAttrValues = r.getData("skuAttrValues", new TypeReference<List<String>>() {
                });
                cartItem.setSkuAttr(skuAttrValues);
            }
        }, threadPoolExecutor);

        CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValuesTask).get();
        // 5.将购物车存入redis
        String cartItemJson = JSON.toJSONString(cartItem);
        operations.put(skuId.toString(), cartItemJson);
        return cartItem;
    }

    @Override
    public CartItem addToCartSuccessPage(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        String s = (String) operations.get(skuId.toString());
        return JSON.parseObject(s, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        // 1.判断是否是登陆状态
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        if (userInfoTO.getUserId() != null) {
            // 登录状态
            String cartKey = CartConstant.CART_PREFIX + userInfoTO.getUserId();
            String tempCartKey = CartConstant.CART_PREFIX + userInfoTO.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null) {
                //临时购物车需要合并
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
                // 清除临时购物车的数据
                clearCart(tempCartKey);
            }
            // 获取登陆后的购物车的数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            String cartKey = CartConstant.CART_PREFIX + userInfoTO.getUserKey();
            // 获取临时购物车的所有数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 获取要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 1.得到用户信息
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        // 2.判断用户是否登录---》决定添加商品到哪个购物车中
        String cartKey = "";
        if (userInfoTO.getUserId() != null) {
            // 用户登录
            cartKey = CartConstant.CART_PREFIX + userInfoTO.getUserId();
        } else {
            cartKey = CartConstant.CART_PREFIX + userInfoTO.getUserKey();
        }
        // 3.返回要操作的购物车
        return stringRedisTemplate.boundHashOps(cartKey);
    }

    /**
     * 获取购物车中的购物项
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if (values != null && values.size() > 0) {
            List<CartItem> cartItemList = values.stream().map(obj -> {
                String str = (String) obj;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
            return cartItemList;
        }
        return null;
    }

    /**
     * 清空购物车
     *
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();

        CartItem cartItem = addToCartSuccessPage(skuId);
        cartItem.setCheck(check == 1);
        String s = JSON.toJSONString(cartItem);
        operations.put(skuId.toString(), s);

    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = addToCartSuccessPage(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> operations = getCartOps();
        operations.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> operations = getCartOps();
        operations.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
        if (userInfoTO.getUserId() == null) {
            return null;
        } else {
            String cartKey = CartConstant.CART_PREFIX + userInfoTO.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            return cartItems.stream().filter(CartItem::getCheck).map(item -> {
                // 更新价格
                R r = productFeignService.getNewPrice(item.getSkuId());
                if (r.getCode() == 0) {
                    BigDecimal newPrice = r.getData("newPrice", new TypeReference<BigDecimal>() {
                    });
                    item.setPrice(newPrice);
                }

                return item;
            }).collect(Collectors.toList());
        }
    }
}
